package com.habdqn.mybatis.demo.dao;

import jdk.internal.util.xml.impl.Input;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * Mybatis工具类，用来获取SqlSession对象
 *
 * @author Xing Jiejian 2019-10-29
 */
public class MybatisUti {
    /**
     * 利用静态成员构建全局唯一的factory对象
     */
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 用来唯一初始化factory对象
     */
    static {
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取SqlSession，不自动提交事务
     *
     * @return sqlSession对象
     */
    public static SqlSession createSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
